在你的faceView class 上面加入 @IBDesignable
在你的屬性上加上 @IBInspectable
型態記得寫上去
這邊新增了一個Model檔案在Controller呼叫
import Foundation
struct FacialExpression {
enum Eye : Int {
case Open
case Closed
case Squinting
}
enum EyeBrows : Int {
case Relaxed
case Normal
case Furrowed
}
enum MouthSmile : Int{
case Happy
case Normal
case Sad
}
var eye:Eye
var brow:EyeBrows
var mouth:MouthSmile
}
Controller如下
import UIKit
class FaceViewController: UIViewController {
//造一個表情
var expression:FacialExpression = FacialExpression(eye: .Open, brow: .Normal, mouth: .Happy){
//建好後必須重畫
didSet{
UpdateUI()
}
}
@IBOutlet var faceView: FaceView! {
//一樣一進去重畫
didSet{
UpdateUI()
}
}
//擺放微笑程度的字典
private var mouthCurve = [FacialExpression.MouthSmile.Happy : 1.0,FacialExpression.MouthSmile.Normal:0.0 , FacialExpression.MouthSmile.Sad:-1.0]
//擺放眉毛八字程度的字典
private var browtilt = [FacialExpression.EyeBrows.Furrowed : -0.5,FacialExpression.EyeBrows.Normal:0.0 , FacialExpression.EyeBrows.Relaxed:0.5]
//把資訊傳進View裡
private func UpdateUI(){
switch expression.eye {
case .Open:faceView.eyesOpen = true
case .Closed:faceView.eyesOpen = false
default:
faceView.eyesOpen = true
}
//重字典取出
faceView.mouthCurve = mouthCurve[expression.mouth] ?? 0.0
faceView.eyeBrowTilt = browtilt[expression.brow] ?? 0.0
}
}
接下來就可以在Controller控制臉的表情了